package com.wandian.view.ui
{
	import com.wandian.core.BitmapManager;
	import com.wandian.core.LoaderManager;
	import com.wandian.data.GameData;
	import com.wandian.data.UIVO;

	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.utils.Dictionary;

	/**
	 * 自动加载UI基类
	 * @author long
	 *
	 */
	public class UILoadingBase extends Sprite
	{
		public var content:MovieClip;
		public var data:Object;
		private var loadingMC:MovieClip;
		private var _uiVO:UIVO;

		public function UILoadingBase(uiVO:UIVO)
		{
			super();
			this.uiVO=uiVO;
			addEventListener(Event.ADDED_TO_STAGE, addToStageHandler);
		}

		private function addToStageHandler(event:Event):void
		{
			init();
			removeEventListener(Event.ADDED_TO_STAGE, addToStageHandler);
		}

		protected function init():void
		{
			if (!this.uiVO)
			{
				return;
			}
			var fileList:Dictionary=LoaderManager.instance.fileList;
			if (fileList[uiVO.swfPath])
			{
				swfLoadComplete();
			}
			else
			{
				LoaderManager.instance.loadItem(uiVO.swfPath, swfLoadComplete, swfLoadError);
				removeLoading();
				var name:String=GameData.MC_LOADING;
				this.loadingMC=BitmapManager.instance.getMCByName(name);
				if (this.loadingMC)
				{
					this.addChild(this.loadingMC);
				}
			}
		}

		protected function swfLoadComplete():void
		{
			removeLoading();
			content=BitmapManager.instance.getMCByName(uiVO.mcName);
			if (content)
			{
				this.addChild(content);

				if (stage)
				{
					this.x=(stage.stageWidth - content.width) / 2;
					this.y=(stage.stageHeight - content.height) / 2;
				}
			}
		}

		protected function swfLoadError():void
		{
			trace("UI 加载出错" + uiVO.swfPath);
		}

		public function get uiVO():UIVO
		{
			return _uiVO;
		}

		public function set uiVO(value:UIVO):void
		{
			_uiVO=value;
		}

		private function removeLoading():void
		{
			if (this.loadingMC)
			{
				if (this.loadingMC.parent)
				{
					this.loadingMC.parent.removeChild(this.loadingMC);
				}
			}
		}

		public function destroy():void
		{
			if (this.content)
			{
				if (this.content.parent)
				{
					this.content.parent.removeChild(this.content);
				}
				this.content=null;
			}
			if (this.parent)
			{
				this.parent.removeChild(this);
			}
		}


	}
}
